<template>
    <div id="container">
    </div>
</template>
<script>
/* eslint-disable no-undef */
export default {
    name: 'amap',
    data() {
        return {
            map: null,
            geolocation: null,
            marker: null
        }
    },
    props: ['markContent', 'center', 'markPosition', 'zoom'],
    methods: {
        initMap() {
            // 初始化高德地图
            this.map = new AMap.Map('container', {
                resizeEnable: true,
                zoom: this.zoom,
                center: this.center,
            })
            this.mark()
        },
        // 地图标记
        mark() {
            this.marker = new AMap.Marker({
                map: this.map,
                position: this.markPosition
            })
            this.marker.setLabel({
                offset: new AMap.Pixel(20, 20), // 修改label相对于maker的位置
                content: this.markContent
            })
        },
        // 执行定位
        Geolocation() {
            this.map.plugin('AMap.Geolocation', () => {
                this.geolocation = new AMap.Geolocation({
                    enableHighAccuracy: true, // 是否使用高精度定位，默认:true
                    timeout: 10000,          // 超过10秒后停止定位，默认：无穷大
                    buttonOffset: new AMap.Pixel(10, 20), // 定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                    zoomToAccuracy: true,      // 定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
                    buttonPosition: 'RB'
                })
                this.map.addControl(this.geolocation)
                this.geolocation.getCurrentPosition()
                AMap.event.addListener(this.geolocation, 'complete', this.onComplete)// 返回定位信息
                AMap.event.addListener(this.geolocation, 'error', this.onError) // 返回定位出错信息
            })
        },
        // 解析定位结果
        onComplete(data) {
            console.log(data)
            var str = ['定位成功']
            str.push('经度：' + data.position.getLng())
            str.push('纬度：' + data.position.getLat())
            if (data.accuracy) {
                str.push('精度：' + data.accuracy + ' 米')
            } // 如为IP精确定位结果则没有精度信息
            str.push('是否经过偏移：' + (data.isConverted ? '是' : '否'))
            console.log(str.join('\n'))
        },
        onError(data) {
            console.log(data.message)
            console.log(data.info)
            console.log('定位失败')
        }
    },
    created() {
        setTimeout(() => {
            this.initMap()
            this.$emit('myamap', this.map, this.marker)
        }, 0)
    }
}
</script>

<style lang="less">
#container {
    width: 100%;
    height: 100%;
}
</style>
